module.exports = (options) => {
  const jwt = require("jsonwebtoken");
  const assert = require("http-assert");
  const AdminUser = require("../models/AdminUser");
  
  return async (req, res, next) => {
    const token = String(req.headers.authorization || "")
      .split(" ")
      .pop();
    //解密出来得到id  没有token
    assert(token, 401, "请先登录");

    const { id } = jwt.verify(token, req.app.get("secret"));
    //token不对
    //再通过id找到数据库里面的用户，最终把user复制给req，挂载到req上面去
    assert(id, 401, "请先登录");

    req.user = await AdminUser.findById(id);
    assert(req.user, 401, "请先登录");

    //console.log(req.user);
    await next();
  };
};
